﻿using Autofac.Extras.DynamicProxy;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using Truron.Purchase.Interface;
using Truron.Purchase.Model;
using Truron.Purchase.Model.RemoteModel;
using Truron.Purchase.Service.DbContext;
using Truron.Purchase.Utility;
using Truron.Purchase.Utility.RedisHelper;

namespace Truron.Purchase.Service
{
    [Intercept(typeof(CustomAutofacAop))]
    public class Purchase_OuterRequestService: IPurchase_OuterRequestService
    {
        private List<Purchase_OuterRequest> Init(bool isInit = false)
        {
            try
            {
                if (isInit)//初始化
                    RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestCacheKey);
                var List = RedisBase.Hash_GetAll<Purchase_OuterRequest>(StaticConstraint.PurchaseOuterRequestCacheKey);
                if (List != null && List.Count > 0)
                    return List;
                string sql = string.Format(@" select a.* from Purchase_OuterRequest a where a.Status!={0} ", (int)Status.delete);
                List = DapperDbContext.Query<Purchase_OuterRequest>(sql).ToList();
                if (List.Count > 0)
                {
                    foreach (var item in List)
                        RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestCacheKey, item.Id, item);
                    RedisBase.Item_SetExpire(StaticConstraint.PurchaseOuterRequestCacheKey, DateTime.Now.AddDays(7));
                }
                return List;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"初始化单据数据失败,isInit:{isInit},详细:{ex.ToString()}");
            }
            return new List<Purchase_OuterRequest>();
        }
        public List<Purchase_OuterRequest> GetAgreeList()
        {
            return Init().Where(x => x.FlowStatus == (int)OuterRequestStatus.agree).OrderBy(x => x.CreateTime).ToList();
        }
        public (int count, List<Purchase_OuterRequest> list) GetList(string searchKey, int pageSize, int pageIndex,string searchJson)
        {
            var queryParam = searchJson.ToJObject();
            int pageNum = (pageIndex - 1) * pageSize;
            var List = Init().OrderBy(x => x.CreateTime).ToList();
            if (!queryParam["beginTime"].IsEmpty())
            {
                List = List.FindAll(x => x.CreateTime >= Convert.ToDateTime(queryParam["beginTime"]));
            }
            if (!queryParam["endTime"].IsEmpty())
            {
                List = List.FindAll(x => x.CreateTime <= Convert.ToDateTime(queryParam["endTime"]));
            }
            if (!queryParam["searchKey"].IsEmpty()||!searchKey.IsEmpty())
            {
                List = List.FindAll(x => x.OrderNo.Contains(searchKey));
            }
            if(!queryParam["type"].IsEmpty())
            {
                if(queryParam["type"].ToString()== "user")
                {
                    List = List.FindAll(x => x.CreateUser==(int)queryParam["value"]);
                }
                else if(queryParam["type"].ToString() == "status")
                {
                    List = List.FindAll(x => x.FlowStatus == (int)queryParam["value"]);
                }
                else if (queryParam["type"].ToString() == "statususer")
                {
                    string[] arr = queryParam["value"].ToString().Split("-");
                    List = List.FindAll(x => x.FlowStatus == Convert.ToInt32(arr[0]) &&x.CreateUser==Convert.ToInt32(arr[1]));
                }
                else if (queryParam["type"].ToString() == "userstatus")
                {
                    string[] arr = queryParam["value"].ToString().Split("-");
                    List = List.FindAll(x => x.FlowStatus == Convert.ToInt32(arr[1]) && x.CreateUser == Convert.ToInt32(arr[0]));
                }
            }
            var ParamList = List.OrderBy(x=>x.CreateTime).Skip(pageNum).Take(pageSize).ToList();
            foreach(var entity in ParamList)
            {
                entity.Auditer = 296;
                entity.AuditerName = "张陶会";
            }
            return (List.Count, ParamList);
        }
        public int Save(Purchase_OuterRequest ent, UserCache user)
        {
            IDbModelService<Purchase_OuterRequest> db = new DbModelService<Purchase_OuterRequest>();
            IDbTransaction transaction = null;
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    transaction = conn.BeginTransaction();
                    if (ent.Id == 0)
                    {
                        ent.Create(user);
                        ent.FlowStatus = (int)OuterRequestStatus.waitapprove;
                        var noteid = db.InsertOne(ent, conn, transaction);
                        ent.Id = noteid;

                        RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestCacheKey, ent.Id,ent);
                        transaction.Commit();
                        return noteid;
                    }
                    else
                    {
                        ent.Modify(user);
                        db.UpdateById(ent, conn, transaction);
                        transaction.Commit();
                        if (ent != null)//更新线索缓存
                        {

                            RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestCacheKey, ent.Id.ToString());
                            RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestCacheKey, ent.Id, ent);
                        }
                        return ent.Id;
                    }

                }
            }
            catch (Exception ex)
            {

                transaction.Rollback();
                return -1;
            }
        }
        public int Del(List<int> Ids, UserCache user)
        {
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    string sql = "UPDATE [dbo].[Purchase_OuterRequest] set [Status] = @Status,[LastUpdateUser] = @LastUpdateUser,[LastUpdateTime] = @LastUpdateTime where Id in @Id";
                    int delcount = conn.Execute(sql, new { Status = Status.delete, LastUpdateUser = user.UserId, LastUpdateTime = DateTime.Now, Id = Ids });
                    if (delcount > 0)
                    {
                        foreach (var id in Ids)
                        {
                            RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestCacheKey, id.ToString());
                        }
                    }
                    return delcount;
                }

            }
            catch (Exception ex)
            {

                return -1;
            }

        }
        public List<ReturnStatusModel> ReturnStatus(List<int> RequestIds)
        {
            List<ReturnStatusModel> results = Init().Where(x=>RequestIds.Contains(x.Id)).Select(x =>new ReturnStatusModel { RequestDId=x.Id, FlowStatus = x.FlowStatus }).ToList();
            return results;
        }
        public void UpdateStatus(int RequestId,int Status,UserCache user)
        {
            Purchase_OuterRequest entity = Init().Find(x => x.Id == RequestId);
            //entity.Modify(user);
            entity.FlowStatus = Status;
            Save(entity, user);

        }
        public List<Purchase_OuterRequest> GetAllList()
        {
            return Init().ToList();
        }
        public Purchase_OuterRequest GetEntityById(int Id)
        {
            return Init().Find(x => x.Id == Id);
        }
    }
    
}
